package com.heima.app.gateway.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.Payload;
import com.heima.utils.common.RsaUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.PublicKey;
import java.util.Date;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Value("${leadnews.jwt.publicKeyPath}")
    private String publicKeyPath;//公钥路径
    /**
     * 编写过滤器逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //对登录请求直接放行
        String uri = request.getURI().getPath();
        if(uri.contains("/login")){
            return chain.filter(exchange);
        }
        //注册放行
        if(uri.contains("/register")){
            return chain.filter(exchange);
        }
        //验证码放行
        if(uri.contains("/appSendSMS")){
            return chain.filter(exchange);
        }


        //取出请求头的token
        String token = request.getHeaders().getFirst("token");

        //判断token是否存在
        if(StringUtils.isEmpty(token)){
            //拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //终止请求
            return response.setComplete();
        }

        //校验token是否合法
        //读取公钥文件
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(publicKeyPath);
            //解析token
            Payload<ApUser> payload = JwtUtils.getInfoFromToken(token, publicKey, ApUser.class);
            //取出token的userId，存入请求头
            ApUser user = payload.getInfo();

            request.mutate().header("userId",user.getId().toString());

            //放行请求
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            //拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //终止请求
            return response.setComplete();
        }
    }

    /**
     * 过滤器执行顺序
     * @return 数值，数值越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
